package com.lovejoanlyn.core;

import android.util.Log;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpContentCompressor;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;

public class NexusService {

    private static final String TAG = "NexusService";

    private static final int DEFAULT_PORT = 8081;

    private static NexusService sInstance;

    private int mPort = DEFAULT_PORT;
    List<String> mRepositories = new ArrayList<>();

    public static NexusService getInstance() {
        if(sInstance == null) {
            synchronized (NexusService.class) {
                sInstance = new NexusService();
            }
        }
        return sInstance;
    }

    public void init(List<String> repositories, int port) {
        mPort = port;
        mRepositories.addAll(repositories);
    }

    public void startServer() {
        try {
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(io.netty.channel.socket.SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // http服务器端对request解码
                            pipeline.addLast(new HttpRequestDecoder());
                            // http服务器端对response编码
                            pipeline.addLast(new HttpResponseEncoder());
                            // 在处理POST消息体时需要加上
                            pipeline.addLast(new HttpObjectAggregator(Integer.MAX_VALUE));
                            // 处理发起的请求
                            pipeline.addLast(new HttpServerHandler(mRepositories));
                            //在HttpResponseEncoder序列化之前会对response对象进行HttpContentCompressor压缩
                            pipeline.addLast("compressor", new HttpContentCompressor());
                        }
                    });
            b.bind(new InetSocketAddress(mPort)).sync();
            Log.d(TAG, "HTTP服务启动成功 PORT=" + mPort);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
